package agend.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DBConnection {

	private static final String DRIVER = "com.mysql.jdbc.Driver";

	private static final String NOME_DB = "sistemintel";
	private static final String NOME_UTENTE = "root";
	private static final String PWD_UTENTE = "root";

	private static final String URL = "jdbc:mysql://localhost:3306/" + NOME_DB + "?user=" + NOME_UTENTE + "&password=" + PWD_UTENTE;

	private static Connection connection = null;

	static {
		try {
			Class.forName(DRIVER);

			connection = DriverManager.getConnection(URL);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static Connection getConnection() {
		if(connection == null)
			rebuildConnection();

		return connection;
	}

	public static void rebuildConnection() {
		try {
			Class.forName(DRIVER);

			connection = DriverManager.getConnection(URL);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void closeConnection()
	{
		try {

			if(connection != null && !connection.isClosed())
				connection.close();

			connection = null;

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void commit() {

		if(connection != null ){
			try {
				
				connection.commit();
				
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}
}
